package wcg;

import java.awt.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Pattern;


public class FileFinder {
	   private File base_;
	    private FileNamePatternFilter filter_;
	    private ArrayList list_;

	    public FileFinder(File base, Pattern pattern) {
	        if (base == null || pattern == null) {
	            throw new NullPointerException();
	        }
	        base_ = base;
	        filter_ = new FileNamePatternFilter(pattern);
	        list_ = new ArrayList();
	        find();
	    }

	    public FileFinder(File base, String regex) {
	        this(base, Pattern.compile(regex));
	    }

	    public FileFinder(String baseDir, String regex) {
	        this(new File(baseDir), Pattern.compile(regex));
	    }

	    public File[] listFiles() {
	        File[] arr = new File[list_.size()];
	        return (File[])list_.toArray(arr);
	    }

	    public String[] list() {
	        ArrayList list = new ArrayList();
	        for (Iterator it = list_.iterator(); it.hasNext();) {
	            list.add(((File)it.next()).getPath());
	        }
	        String[] arr = new String[list.size()];
	        return (String[])list.toArray(arr);
	    }

	    public void print() {
	        String[] lists = list();
	        for (int i = 0; i < lists.length; i++) {
	            System.out.println(lists[i]);
	        }
	    }

	    public void find() {
	        list_.clear();
	        findPattern(base_);
	        findDirectory(base_.listFiles());
	    }

	    private void findDirectory(File[] baseDirs) {
	        for (int i = 0; i < baseDirs.length; i++) {
	            findPattern(baseDirs[i]);
	            if (baseDirs[i].isDirectory()) {
	                findDirectory(baseDirs[i].listFiles());
	            }
	        }
	    }

	    private void findPattern(File directory) {
	        File[] matches = directory.listFiles(filter_);
	        for (int i = 0; i < matches.length; i++) {
	            list_.add(matches[i]);
	        }
	    }

	    // print.
	    public static void main(String[] args) {
	        try {
	            FileFinder finder = new FileFinder(args[0], args[1]);
	            finder.print();
	        } catch (Exception e) {
	            System.err
	                .println("Usage:java com.fc2web.himtodo.FileFinder"
	                        + " directory regex");
	            System.exit(-1);
	        }
	    }

}
